/**
 * @desc saveFile & getFileInfo & getSavedFileList& getSavedFileInfo & removeSaveFile & openDocument
 * 
 */

const upload = require('../network/request.js').upload
const config = require('../../../utils/config.js');

const file={
  saveFile(src){
    return new Promise((resolve,reject)=>{
      wx.saveFile({
        tempFilePath: src,
        success:function(res){
          resolve(res);
        },
        fail:function(error){
          reject(error)
        }
      })
    })

  },

  getFileInfo(src){
    return new Promise((resolve, reject) => {
      wx.getFileInfo({
        success(res) {
          resolve(res);
        },
        fail:function(error){
          reject(error)
        }
      })
    }) 
  },

  removeSaveFile(src) {
    return new Promise((resolve, reject) => {
      wx.getSavedFileList({
        success: function (res) {
          if (res.fileList.length > 0) {
            for(let i in res.fileList){
              wx.removeSavedFile({
                filePath: res.fileList[i].filePath,
                complete: function (complete) {
                  if(i===res.fileList-1) resolve();
                }
              })
            }
          }else{
            reject();
          }
        }
      })
    }) 
  },

  openDocument(src){
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url: src,
        success: function (res) {
          var filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            success: function (res) {
              console.log('打开文档成功');
              resolve();
            },
            fail:function(){
              reject();
            }
          })
        }
      })
    })
  },

  downloadFile(url) {
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url,
        success: res => {
          resolve(res.tempFilePath)
        },
        fail: err => {
          reject(err)
        }
      })
    })
  }

}

module.exports = {
  file
}